﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class panel_ExportRobotPlan : UserControl
    {
        public panel_ExportRobotPlan()
        {
            InitializeComponent();
            mySetting = new INISettings();
            myConnection = new SqlConnection(mySetting.SQLConnectionString);
            LoadData();
            this.ExportRobotPlan.PopupMenuShowing += ExportRobotPlan_PopupMenuShowing;
            this.exportRobotContextMenu.ItemClicked += exportRobotContextMenu_ItemClicked;
            this.ExportRobotPlan.DoubleClick += ExportRobotPlan_DoubleClick;
        }

        //////////////////////////////////////////
        /// Call Edit Form
        ///////////////////////////////////////////
        private void callEditForm()
        {
            DataRow row = ExportRobotPlan.GetFocusedDataRow();
            if ((bool)row["Exported"])
            {
                MessageBox.Show("This number has been finished");
            }
            else
            {
                if ((bool)row["ChangeOrCancel"])
                {
                    MessageBox.Show("This number has been changed");
                }
                else
                {
                    frm_Edit_ExportRobotPlan edit_Form = new frm_Edit_ExportRobotPlan();
                    edit_Form.number = row["Number"].ToString();
                    if (edit_Form.LoadData())
                    {
                        //edit_Form.Show();
                        edit_Form.ShowDialog();
                        LoadData();
                    }
                    else
                    {
                        edit_Form.Dispose();
                        MessageBox.Show("Cannot load data for selected record");
                    }
                }
            } 
        }

        //////////////////////////////////////////
        /// Call Revise Form
        //////////////////////////////////////////
        private void callReviseForm()
        {
            DataRow row = this.ExportRobotPlan.GetFocusedDataRow();
            if ((bool)row["Exported"])
            {
                MessageBox.Show("This number has been finished");
            }
            else
            {
                if ((bool)row["ChangeOrCancel"])
                {
                    MessageBox.Show("This number has been changed");
                }
                else
                {
                    frm_Revise_ExportRobotPlan revise_Form = new frm_Revise_ExportRobotPlan();
                    revise_Form.number = row["Number"].ToString();
                    if (revise_Form.LoadData())
                    {
                        //revise_Form.Show();
                        revise_Form.ShowDialog();
                    }
                    else
                    {
                        revise_Form.Dispose();
                        MessageBox.Show("Cannot load data for selected record");
                    }
                }
            }
        }

        ////////////////////////////////
        /// Cancel Plan
        ///////////////////////////////
        private void cancelPlan()
        {
            DataRow row = this.ExportRobotPlan.GetFocusedDataRow();
            if ((bool)row["Exported"])
            {
                MessageBox.Show("This number has been finished");
            }
            else
            {
                if ((bool)row["ChangeOrCancel"])
                {
                    MessageBox.Show("This number has been changed");
                }
                else
                {
                    if (MessageBox.Show("Really cancel?", "Confirm cancel", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        try
                        {
                            myConnection.Open();
                            string sql = "UPDATE [241_ExportRobotPlan] SET Exported=1,"
                                + " ChangeContent='Cancel on " + DateTime.Now.Date.ToShortDateString() + "',"
                                + " ChangeOrCancel=1 WHERE Number='" + row["Number"].ToString() + "'";
                            SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                            cmd_sql.ExecuteNonQuery();
                            cmd_sql.Dispose();
                            myConnection.Close();
                            MessageBox.Show("The Number " + row["Number"].ToString() + " has been cancelled success!");
                            LoadData();
                        }
                        catch (Exception ex)
                        {
                            if (myConnection.State == ConnectionState.Open)
                            {
                                myConnection.Close();
                            }
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
            }
        }

        void ExportRobotPlan_DoubleClick(object sender, EventArgs e)
        {
            callEditForm();
        }

        void exportRobotContextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.exportRobotContextMenu.Hide();
            DataRow row = this.ExportRobotPlan.GetFocusedDataRow();
            switch (e.ClickedItem.Name)
            {
                case "changeSelection":
                    callEditForm();                    
                    break;
                case "reviseSelection":
                    callReviseForm();
                    break;
                case "cancelSelection":
                    cancelPlan();
                    break;
                case "addnewSelection":
                    frm_Add_ExportRobotPlan add_Form = new frm_Add_ExportRobotPlan();
                    //add_Form.Show();
                    add_Form.ShowDialog();
                    break;
                case "refreshSelection":
                    LoadData();
                    break;
            }
        }

        void ExportRobotPlan_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            this.exportRobotContextMenu.Show(MousePosition);            
        }       

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            frm_Add_ExportRobotPlan add_Form = new frm_Add_ExportRobotPlan();
            //add_Form.Show();
            add_Form.ShowDialog();
            LoadData();
        }

        
        /////////////////////////////////////////
        /// Load Export Robot Plan into gridview
        /////////////////////////////////////////
        private void LoadData()
        {            
            DataSet sourceDataSet = new DataSet();
            SQLManagement mySQLManagement = new SQLManagement();
            mySQLManagement.SQLConnectionString = mySetting.SQLConnectionString;
            string sql = "SELECT [241_ExportRobotPlan].Number, [241_ExportRobotPlan].InputDate, [222_Staff].StaffName,"
                + " [222_Customer].FullName, [222_ShipTo].ShipToName, [241_ExportRobotPlan].PlanNo, [241_ExportRobotPlan].RobotNo,"
                + " [241_ExportRobotPlan].Quantity, [241_ExportRobotPlan].POID, [241_ExportRobotPlan].CusPlanNo,"
                + " [241_ExportRobotPlan].CusOrderNo, [241_ExportRobotPlan].HopeDeadline, [241_ExportRobotPlan].UnitPrice,"
                + " [222_Currency].CurrencySymbol, [222_DeliveryTerm].DeliveryTermName, [222_Transport].TransportName,"
                + " [241_ExportRobotPlan].FixDeadline, [241_ExportRobotPlan].F2Deadline, [241_ExportRobotPlan].F5Deadline,"
                + " [241_ExportRobotPlan].OImportDeadline, [241_ExportRobotPlan].VNImportDeadline, [241_ExportRobotPlan].StoreDeadline,"
                + " [241_ExportRobotPlan].AssDeadline, [241_ExportRobotPlan].F4Order, [241_ExportRobotPlan].DocFinish,"
                + " [241_ExportRobotPlan].Exported, [241_ExportRobotPlan].ExportDate, [241_ExportRobotPlan].ChangeContent,"
                + " [241_ExportRobotPlan].ChangeOrCancel, [241_ExportRobotPlan].Note, [241_ExportRobotPlan].CusArrival,"
                + " [241_ExportRobotPlan].OriginalNo"
                + " FROM [241_ExportRobotPlan] LEFT OUTER JOIN"
                + " [222_Staff] ON [241_ExportRobotPlan].InputPerson = [222_Staff].StaffID LEFT OUTER JOIN"
                + " [222_Customer] ON [241_ExportRobotPlan].CustomerID = [222_Customer].CustomerID LEFT OUTER JOIN"
                + " [222_ShipTo] ON [241_ExportRobotPlan].ShipToCode = [222_ShipTo].ShipToCode LEFT OUTER JOIN"
                + " [222_Currency] ON [241_ExportRobotPlan].CurrencyID = [222_Currency].CurrencyID LEFT OUTER JOIN"
                + " [222_DeliveryTerm] ON [241_ExportRobotPlan].DeliveryTermID = [222_DeliveryTerm].DeliveryTermID LEFT OUTER JOIN"
                + " [222_Transport] ON [241_ExportRobotPlan].TransportID = [222_Transport].TransportID";
            sourceDataSet = mySQLManagement.SQL_Query(sql);
            if (sourceDataSet != null)
            {
                gridExportRobotPlan.DataSource = sourceDataSet.Tables[0];
            }
            else
            {
                MessageBox.Show("There is no data for Export Robot Plan");
                DataTable newTable = new DataTable();
                newTable.Columns.Add("Number", typeof(string));
                newTable.Columns.Add("InputDate", typeof(DateTime));
                newTable.Columns.Add("InputPerson", typeof(string));
                newTable.Columns.Add("CustomerID", typeof(string));
                newTable.Columns.Add("ShipTo", typeof(string));
                newTable.Columns.Add("PlanNo", typeof(string));
                newTable.Columns.Add("RobotNo", typeof(string));
                newTable.Columns.Add("Quantity", typeof(int));
                newTable.Columns.Add("POID", typeof(string));
                newTable.Columns.Add("CusPlanNo", typeof(string));
                newTable.Columns.Add("CusOrderNo", typeof(string));
                newTable.Columns.Add("HopeDeadline", typeof(DateTime));
                newTable.Columns.Add("UnitPrice", typeof(float));
                newTable.Columns.Add("CurrencyID", typeof(int));
                newTable.Columns.Add("DeliveryTerm", typeof(string));
                newTable.Columns.Add("TransportID", typeof(string));
                newTable.Columns.Add("FixDeadline", typeof(DateTime));
                newTable.Columns.Add("F2Deadline", typeof(DateTime));
                newTable.Columns.Add("F5Deadline", typeof(DateTime));
                newTable.Columns.Add("OImportDeadline", typeof(DateTime));
                newTable.Columns.Add("VNImportDeadline", typeof(DateTime));
                newTable.Columns.Add("StoreDeadline", typeof(DateTime));
                newTable.Columns.Add("AssDeadline", typeof(DateTime));
                newTable.Columns.Add("F4Order", typeof(bool));
                newTable.Columns.Add("DocFinish", typeof(bool));
                newTable.Columns.Add("Exported", typeof(bool));
                newTable.Columns.Add("ExportDate", typeof(DateTime));
                newTable.Columns.Add("ChangeContent", typeof(string));
                newTable.Columns.Add("ChangeOrCancel", typeof(bool));
                newTable.Columns.Add("Note", typeof(string));
                newTable.Columns.Add("CusArrival", typeof(DateTime));
                newTable.Columns.Add("OriginalNo", typeof(string));
                gridExportRobotPlan.DataSource = newTable;
            }
            ExportRobotPlan.Columns[0].Caption = "Number";
            ExportRobotPlan.Columns[1].Caption = "Input Date";
            ExportRobotPlan.Columns[2].Caption = "Input Person";
            ExportRobotPlan.Columns[3].Caption = "Customer";
            ExportRobotPlan.Columns[4].Caption = "Ship To";
            ExportRobotPlan.Columns[5].Caption = "Plan No";
            ExportRobotPlan.Columns[6].Caption = "Robot No";
            ExportRobotPlan.Columns[7].Caption = "Quantity";
            ExportRobotPlan.Columns[8].Caption = "PO ID";
            ExportRobotPlan.Columns[9].Caption = "Cus. Plan No";
            ExportRobotPlan.Columns[10].Caption = "Cus. Order No";
            ExportRobotPlan.Columns[11].Caption = "Hope Deadline";
            ExportRobotPlan.Columns[12].Caption = "Unit Price";
            ExportRobotPlan.Columns[13].Caption = "Currency";
            ExportRobotPlan.Columns[14].Caption = "Delivery Term";
            ExportRobotPlan.Columns[15].Caption = "Transport";
            ExportRobotPlan.Columns[16].Caption = "Fix Deadline";
            ExportRobotPlan.Columns[17].Caption = "F2 Deadline";
            ExportRobotPlan.Columns[18].Caption = "F5 Deadline";
            ExportRobotPlan.Columns[19].Caption = "O Import Deadline";
            ExportRobotPlan.Columns[20].Caption = "VN Import Deadline";
            ExportRobotPlan.Columns[21].Caption = "Store Deadline";
            ExportRobotPlan.Columns[22].Caption = "Ass Deadline";
            ExportRobotPlan.Columns[23].Caption = "F4 Order";
            ExportRobotPlan.Columns[24].Caption = "Doc Finish";
            ExportRobotPlan.Columns[25].Caption = "Exported";
            ExportRobotPlan.Columns[26].Caption = "Export Date";            
            ExportRobotPlan.Columns[27].Caption = "Change Content";
            ExportRobotPlan.Columns[28].Caption = "Change Or Cancel";
            ExportRobotPlan.Columns[29].Caption = "Note";
            ExportRobotPlan.Columns[30].Caption = "Cus. Arrival";
            ExportRobotPlan.Columns[31].Caption = "Original No";
            ExportRobotPlan.BestFitColumns();
        }

        ///////////////////////////////////////
        /// Calculate Part List for Comp
        ///////////////////////////////////////
        private List<string[]> totalList = new List<string[]>();        
        private List<string[]> currentLevel = new List<string[]>();
        private List<string[]> nextLevel = new List<string[]>();
        private void getPartListForRobot(string exportnumber, string robotnumber)
        {            
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT * FROM [222_Kosei] WHERE CompID='" + robotnumber + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    if (dataReader["PartNo"] == DBNull.Value)
                    {
                        string[] a = new string[3];
                        a[0] = exportnumber;
                        a[1] = robotnumber;
                        a[2] = dataReader["CompID"].ToString();
                        a[3] = dataReader["Quantity"].ToString();
                        totalList.Add(a);
                    }
                    else
                    {
                        string[] b = new string[3];
                        b[0] = exportnumber;
                        b[1] = robotnumber;
                        b[2] = dataReader["PartNo"].ToString();
                        b[3] = dataReader["Quantity"].ToString();
                        nextLevel.Add(b);
                    }
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();

                if (nextLevel.Count > 0)
                {
                    loopComp();
                }                
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Part list for Comp: " + robotnumber);
            }
        }

        //////////////////////////////////////
        /// Loop to find detail of Comp
        //////////////////////////////////////
        private void loopComp()
        {
            currentLevel = nextLevel;
            nextLevel.Clear();
            for (int i = 0; i < currentLevel.Count; i++)
            {
                string[] row = new string[3];
                row = nextLevel[i];
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT * FROM [222_Kosei] WHERE CompID='" + row[2] + "'";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    while (dataReader.Read())
                    {
                        if (dataReader["PartNo"] == DBNull.Value)
                        {
                            string[] a = new string[3];
                            a[0] = row[0];
                            a[1] = row[1];
                            a[2] = dataReader["CompID"].ToString();
                            a[3] = (Int32.Parse(dataReader["Quantity"].ToString()) * Int32.Parse(row[3])).ToString();
                            totalList.Add(a);
                        }
                        else
                        {
                            string[] b = new string[3];
                            b[0] = row[0];
                            b[1] = row[1];
                            b[2] = dataReader["PartNo"].ToString();
                            b[3] = dataReader["Quantity"].ToString();
                            nextLevel.Add(b);
                        }
                    }
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();                    
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Cannot get Part list for Comp: " + row[1]);
                }
            }

            if (nextLevel.Count > 0)
            {
                loopComp();
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            callEditForm();
        }

        private void buttonRevise_Click(object sender, EventArgs e)
        {
            callReviseForm();
        }

        private void buttonDevide_Click(object sender, EventArgs e)
        {
            //callDevideForm();
        }
    }
}
